
import { _decorator, Component, Vec2, RigidBody2D, Animation, Sprite, Contact2DType, CircleCollider2D, Collider2D, IPhysics2DContact, CCInteger, Vec3 } from 'cc';
import { Enemy } from './animy/Enemy';
import { SteelGun } from './animy/SteelGun';
import { ColliderTag, ObjectAtks } from './Globle';
import { MoveObject } from './MoveObject';
const { ccclass } = _decorator;

@ccclass('Bullet')
export class Bullet extends MoveObject {
    public ATK:number = ObjectAtks.bullet;
    private direction: Vec2;
    private fly_distance:number = 100;
    private rigidbody: RigidBody2D;
    private collider: CircleCollider2D;
    public speed: number = 5;
    private type: 'enemy' | 'player' = 'enemy';
    private start_position:Vec3;
    onLoad() {
        this.rigidbody = this.getComponent(RigidBody2D);
        this.collider = this.getComponent(CircleCollider2D);
        this.rigidbody.enabledContactListener = true;
        if (this.collider) {
            this.collider.on(Contact2DType.BEGIN_CONTACT, this.onContact, this);
        }
    }

    public setDirection(direction: Vec2, type: 'enemy' | 'player',fly_distance?:number) {
        this.start_position = this.node.position.clone();
        if(fly_distance) this.fly_distance = fly_distance;
        this.type = type;
        let firme = this.getComponent(Sprite).spriteAtlas.getSpriteFrame('bullet_01');
        this.getComponent(Sprite).spriteFrame = firme;
        this.direction = direction;
        this.rigidbody.linearVelocity = direction.set(direction.x * this.speed, direction.y * this.speed);
    }

    private onContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
        switch (otherCollider.tag) {
            case ColliderTag.wall://障碍物
                this.animateEnd()
                break;
            case ColliderTag.attackedWall:
                this.animateEnd();
                break;
            case ColliderTag.enemyWall:
                if (this.type == 'player') {
                    this.animateEnd()
                }
                break;
            case ColliderTag.enemy_people:
            case ColliderTag.enemy:
                if (this.type == 'player') {
                    let obj = otherCollider.node.getComponent(Enemy);
                    if (obj) obj.onContact(selfCollider);
                    this.animateEnd()
                }
                break;
        }
    }

    update(deltaTime: number){
        if(!this.node.active) return;
        let distance = this.node.position.clone().subtract(this.start_position).length();
        if(distance>=this.fly_distance){
            this.rigidbody.linearVelocity = Vec2.ZERO;
            this.node.active = false;
        }
    }

    /**销毁子弹
     * animateEnd
     */
    public animateEnd() {
        if(!this.node.active) return;
        this.rigidbody.linearVelocity = Vec2.ZERO;
        this.scheduleOnce(()=>this.node.active = false,0.01);
    }
}
